package com.house.auth.service.impl;

import com.house.auth.config.JwtUtil;
import com.house.auth.dao.PowerDao;
import com.house.auth.entity.PowerEntity;
import com.house.auth.service.PowerService;
import com.house.common.to.UserTo;
import com.house.common.utils.R;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.house.common.utils.PageUtils;
import com.house.common.utils.Query;

import javax.servlet.http.HttpServletRequest;


@Service("powerService")
public class PowerServiceImpl extends ServiceImpl<PowerDao, PowerEntity> implements PowerService {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PowerEntity> page = this.page(
                new Query<PowerEntity>().getPage(params),
                new QueryWrapper<PowerEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R createToken(UserTo user) {
        Long pid = user.getPid();
        PowerEntity powerEntity = baseMapper.selectById(pid);
        if (powerEntity.getPowerLogin() == 1){
            String token = jwtUtil.createJWT(user.getUid().toString(), user.getNickname(), user.getPid().toString());
            return R.ok().put("token",token);
        }else {
            return R.error(50000,"登录权限异常");
        }
    }

    @Override
    public R getId(HttpServletRequest request) {
        String token = request.getHeader("token");
        Claims claims = jwtUtil.parseJWT(token);
        if (claims == null) {
            return R.error(50006,"token解析失败");
        }else {
            return R.ok().put("userId",claims.getId());
        }
    }

    @Override
    public R feignGetId(String token) {
        Claims claims = jwtUtil.parseJWT(token);
        if (claims != null){
            return R.ok().put("userId",Integer.parseInt(claims.getId()));
        }else {
            return R.error(50006,"token解析失败").put("userId",-1);
        }
    }

}